package com.martin.lib_base.binding.adapter

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Build
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.GranularRoundedCorners
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.martin.lib_base.base.BaseViewHolder
import com.martin.lib_base.common.CommonAdapter
import com.martin.lib_base.ktx.logw
import dev.utils.app.SizeUtils

/**
 * @author：Houge
 * @date：2022/11/11
 * @desc：dataBinding适配器
 */
/**
 * 加载图片
 */
@SuppressLint("CheckResult")
@BindingAdapter(
    // 图片地址
    "loadImage",
    // 错误图片
    "loadError",
    // 占位图
    "loadPlaceholder",
    // 宽度
    "loadWidth",
    // 高度
    "loadHeight",
    // 是否缓存
    "loadCache",
    // 加载圆形图片
    "loadCircle",
    // 圆角
    "loadRadius",
    /**
     * 下述圆角参数优先级高于 loadRadius 和 loadCircle,
     * 并且设置了单个圆角参数后,就会生效,未设置的参数默认为0
     */
    //左上角圆角
    "loadRadiusTopLeft",
    // 右上角圆角
    "loadRadiusTopRight",
    // 左下角圆角
    "loadRadiusBottomLeft",
    // 右下角圆角
    "loadRadiusBottomRight",
    requireAll = false
)
fun loadImage(
    imageView: ImageView,
    source: Any? = null,
    error: Any? = null,
    placeholder: Any? = null,
    width: Int? = 0,
    height: Int? = 0,
    cacheEnable: Boolean? = true,
    circle: Boolean? = false,
    radius: Any? = null,
    radiusTopLeft: Any? = null,
    radiusTopRight: Any? = null,
    radiusBottomLeft: Any? = null,
    radiusBottomRight: Any? = null
) {
    // 获取当前的Activity
    val activity: Activity? = when (imageView.context) {
        is Activity -> {
            imageView.context as Activity
        }

        is Fragment -> {
            (imageView.context as Fragment).requireActivity()
        }

        else -> {
            null
        }
    }
    // 如果当前的Activity已经销毁，就不加载图片
    if (activity?.isDestroyed != false) {
        return
    }
    // 根据定义的 cacheEnable 参数来决定是否缓存
    val diskCacheStrategy =
        if (cacheEnable == true)
            DiskCacheStrategy.AUTOMATIC else DiskCacheStrategy.NONE
    // 设置编码格式，在Android 11(R)上面使用高清无损压缩格式 WEBP_LOSSLESS ，
    // Android 11 以下使用PNG格式，PNG格式时会忽略设置的 quality 参数。
    val encodeFormat =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
            Bitmap.CompressFormat.WEBP_LOSSLESS else Bitmap.CompressFormat.PNG

    // 设置图片加载
    val load = Glide.with(imageView)
        .load(source)
        .diskCacheStrategy(diskCacheStrategy)
        .encodeFormat(encodeFormat)

    // 设置错误图片
    error?.let {
        load.error(error)
    }

    // 设置占位图
    placeholder?.let {
        if (it is Drawable) {
            load.placeholder(it)
        }
        if (it is Int) {
            load.placeholder(it)
        }
    }

    // 设置宽高
    if ((width ?: 0) > 0 && (height ?: 0) > 0)
        load.override(width!!, height!!)

    // 判定是否设置了四个圆角
    if (radiusTopLeft != null || radiusTopRight != null || radiusBottomLeft != null || radiusBottomRight != null) {
        load.transform(
            CenterCrop(),
            GranularRoundedCorners(
                getSize(radiusTopLeft).toFloat(),
                getSize(radiusTopRight).toFloat(),
                getSize(radiusBottomRight).toFloat(),
                getSize(radiusBottomLeft).toFloat(),
            )
        )
    } else if (radius != null) {
        load.transform(CenterCrop(), RoundedCorners(getSize(radius)))
    } else if (circle == true) {
        // 设置圆形图片
        load.circleCrop()
    }

    // 设置图片到控件
    load.into(imageView)
}

/**
 * 设置通用adapter
 */
@BindingAdapter("viewHolders")
fun setCommonAdapter(
    rv: RecyclerView,
    holderClass: List<Class<out BaseViewHolder<*, out ViewDataBinding>>>
) {
    logw("holderClass ====== $holderClass")
    val customAdapter = CommonAdapter(rv.context, holderClass)
    rv.adapter = customAdapter
}

/**
 * 获取尺寸
 * 这里只支持dp
 * [SizeUtils] 是尺寸工具类,可以在代码库中获取
 */
private fun getSize(size: Any?): Int {
    return try {
        SizeUtils.dp2px(size.toString().toFloat())
    } catch (e: Exception) {
        0
    }
}